import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterdemo/http/http.dart';
import 'package:flutterdemo/utils/sp_util.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class HttpPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HttpPageState();
  }
}

class _HttpPageState extends State<HttpPage> {
  String path =
      '/data/user/0/com.jzqf.flutterdemo/cache/image_picker8958103488097939632.jpg';
  String videoPath =
      '/data/user/0/com.jzqf.flutterdemo/cache/image_picker4316068622279735707.jpg';
  Dio dio;

  @override
  void initState() {
    super.initState();
    HttpManager().baseUrl = 'https://xxxxxxx/';
    var options = new BaseOptions(
      baseUrl: HttpManager().baseUrl,
      responseType: ResponseType.plain,
//        contentType: Headers.jsonContentType,
    );
    dio = new Dio(options);
    dio.interceptors.add(new LogInterceptors());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(54),
        child: AppBar(
          //标题居中
          centerTitle: true,
          //状态栏样式
          brightness: Brightness.light,
          title: Text(
            "dio网络请求",
            style: TextStyle(
              fontSize: 19,
              color: Colors.redAccent,
            ),
          ),
          elevation: 0,
          backgroundColor: Colors.white,
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pop(context, 1);
            },
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: _body(),
      ),
    );
  }

  Widget _body() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        RaisedButton(
          child: Text('get'),
          onPressed: () async {
            HttpManager().get(
              'LockConstruction/GetCityList',
              null,
              (data) {},
              (error) {},
            );
          },
        ),
        RaisedButton(
          child: Text('post'),
          onPressed: () async {
            HttpManager().post(
              'register',
              {'account': "872235631", 'password': '123456'},
              (data) {},
              (error) {},
            );
          },
        ),
        Row(
          children: <Widget>[
            IconButton(
              icon: Image.file(
                File(path),
              ),
              iconSize: 150,
              onPressed: () {
                _imagePicker();
              },
            ),
            IconButton(
              icon: Image.file(
                File(videoPath),
              ),
              iconSize: 150,
              onPressed: () {
                _videoPicker();
              },
            ),
          ],
        ),
        RaisedButton(
          child: Text('下载文件'),
          onPressed: () {
            _external();
            _downloadFile();
          },
        ),
        RaisedButton(
          child: Text('上传文件'),
          onPressed: () async {
            FormData formData = FormData.fromMap({
              "des": "文件描述",
              "file": await MultipartFile.fromFile(path),
            });
            HttpManager().post("upload", formData, (data) {}, (error) {});
          },
        ),
        RaisedButton(
          child: Text('多上传文件'),
          onPressed: () async {
            FormData formData = FormData.fromMap({
              "des": "文件描述",
              "files": [
                await MultipartFile.fromFile(path),
                await MultipartFile.fromFile(path),
              ],
            });
            HttpManager().post('uploads', formData, (data) {}, (error) {});
          },
        ),
        RaisedButton(
          child: Text('获取token'),
          onPressed: () async {
            HttpManager()
                .post("login", {'account': "872235631", 'password': '123456'},
                    (data) {
              String token = data['data']['token'];
              print('[token]$token');
              SpUtil().putString("token", token);
            }, (error) {});
          },
        ),
        RaisedButton(
          child: Text('自动获取token'),
          onPressed: () async {
            _token();
          },
        ),
      ],
    );
  }

  Future _imagePicker() async {
    PickedFile pickedFile =
        await ImagePicker().getImage(source: ImageSource.gallery);
    if (pickedFile == null) {
      return;
    }
    print('path=${pickedFile.path}');
    setState(() {
      path = pickedFile.path;
    });
  }

  Future _videoPicker() async {
    PickedFile pickedFile =
        await ImagePicker().getVideo(source: ImageSource.gallery);
    if (pickedFile == null) {
      print('#####pickedFile is null');
      return;
    }
    print('video path=${pickedFile.path}');
    setState(() {
      videoPath = pickedFile.path;
    });
  }

  _downloadFile() async {
    await dio.download('https://www.baidu.com/',
        (await getExternalStorageDirectory()).path + "/baidu.xml");
    var response = await dio.download(
        'https://bucketjerry.oss-cn-qingdao.aliyuncs.com/manager_20200720_1056_1.9.apk?Expires=1595294663&OSSAccessKeyId=TMP.3Khju5uEPDBDYr9tGTzPdCbkfKEpfeL1T3vaviA65z2QPDwELZUePYuvt1Ycamd8PDb8EmFaVzVc6Sz19xtjB5UPpZYrq1&Signature=IqtRyPopoQB%2BbHe%2FC%2BnH%2BknQYdw%3D',
        (await getExternalStorageDirectory()).path + "/io_manager.apk");
  }

  _external() async {
    print('[getDatabasesPath]${await getDatabasesPath()}');
    print('[getTemporaryDirectory]${(await getTemporaryDirectory()).path}');
    print(
        '[getExternalStorageDirectory]${(await getExternalStorageDirectory()).path}');
    print(
        '[getApplicationDocumentsDirectory]${(await getApplicationDocumentsDirectory()).path}');
    print(
        '[getApplicationSupportDirectory]${(await getApplicationSupportDirectory()).path}');
    if (Platform.isIOS) {
      print('[getDownloadsDirectory]${(await getDownloadsDirectory()).path}');
      print('[getLibraryDirectory]${(await getLibraryDirectory()).path}');
    }
  }

  String token;

  Future _token() async {
    Dio dio = Dio();
    Dio dioToken = Dio();
    BaseOptions options = BaseOptions(
      baseUrl: 'http://xxxxxxxx/',
      contentType: Headers.formUrlEncodedContentType,
      headers: {"terminal": "Android"},
    );
    dio.options = options;
    dioToken.options = options;
    dio.interceptors.add(LogInterceptors());
    dioToken.interceptors.add(LogInterceptors());
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (Options requestOptions) async {
        if (token == null) {
          dio.lock();
          var response = await dioToken.post(
            'token/login',
            data: {
              "username": "NZ",
              "password": "123456",
              "terminal": "Android"
            },
          );
          requestOptions.headers['Authorization'] =
              response.data['rows'][token];
          dio.unlock();
          return requestOptions;
        } else {
          requestOptions.headers['Authorization'] = token;
          return requestOptions;
        }
      },
    ));
    var response = await dio.post(
      'department/selectAllDepartment',
    );
  }
}
